package com.hly.wms.service.impl;

import com.hly.common.constant.WareConstant;
import com.hly.wms.entity.PurchaseDetailEntity;
import com.hly.wms.entity.SysUserEntity;
import com.hly.wms.feign.RenRenFeign;
import com.hly.wms.service.PurchaseDetailService;
import com.hly.wms.service.WareSkuService;
import com.hly.wms.vo.MergeVo;
import com.hly.wms.vo.PurchaseDoneVo;
import com.hly.wms.vo.PurchaseItemDoneVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hly.common.utils.PageUtils;
import com.hly.common.utils.Query;

import com.hly.wms.dao.PurchaseDao;
import com.hly.wms.entity.PurchaseEntity;
import com.hly.wms.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private RenRenFeign renRenFeign;
    @Autowired
    private WareSkuService wareSkuService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        String status = (String) params.get("status");
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(status)){
            wrapper.eq("status",status);
        }
        if(StringUtils.isNotEmpty(key)){
            wrapper.and(i -> i.eq("id",key).or().eq("assignee_id",key).or().like("assignee_name",key));
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 合并采购单
     * @param mergeVo
     * @return
     */
    @Transactional
    @Override
    public boolean MergerOrder(MergeVo mergeVo) {
        String purchaseId = mergeVo.getPurchaseId();

        //确认采购是 0 或 1 才可以合并
        for (Long id:mergeVo.getItems()
        ) {
            PurchaseDetailEntity byId = purchaseDetailService.getById(id);
            if(Integer.valueOf(byId.getStatus()) != 0 && Integer.valueOf(byId.getStatus()) != 1){
                return false;
            }
        }

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        //判断订单是否存在
        if(StringUtils.isEmpty(purchaseId)){
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
//            purchaseEntity.setCreateTime(new Date());
//            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        String finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = mergeVo.getItems().stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();

            purchaseDetailEntity.setId(String.valueOf(item));
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            purchaseDetailEntity.setPurchaseId(Long.valueOf(finalPurchaseId));
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);

        purchaseEntity.setId(finalPurchaseId);
//        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
        return true;
    }

    /**
     * 分配采购单，采购人员
     * @param assigneeId
     * @param id
     * @return
     */
    @Transactional
    @Override
    public boolean updateByIdOfUser(Integer assigneeId, Integer id) {
        SysUserEntity userEntity = (SysUserEntity)renRenFeign.selectById(assigneeId);
        PurchaseEntity byId = this.getById(id);
        byId.setAssigneeId(userEntity.getUserId());
        byId.setAssigneeName(userEntity.getUsername());
        byId.setPhone(userEntity.getMobile());
        //判断是否已领取，领取则不用改状态
        if(!(byId.getStatus() == WareConstant.PurchaseStatusEnum.RECEIVE.getCode())){
            byId.setStatus(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
        }
        if(this.updateById(byId)){
            return true;
        }
        return false;
    }

    /**
     * 领取采购单业务
     * @param items 采购单id集合
     */
    @Override
    public void received(List<Long> items) {
        // 1、确认当前采购单是 新建或者 已分配状态 才能进行采购
        List<PurchaseEntity> collect = items.stream().map(item -> {
            // 根据采购id查询出采购信息
            PurchaseEntity byId = this.getById(item);
            return byId;
        }).filter(byId -> {
            // 新建或者已分配留下
            if (byId.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    byId.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).map(byId -> {
            // 设置为已领取
            byId.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return byId;
        }).collect(Collectors.toList());
        // 2、改变采购单状态
        this.updateBatchById(collect);

        // 3、改变采购项的状态
        collect.stream().forEach(purchaseEntity -> {

            // 根据 purchase_id 查询出采购需求
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchaseId(purchaseEntity.getId());

            List<PurchaseDetailEntity> collect1 = purchaseDetailEntities.stream().map(entity -> {

                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(entity.getId());
                // 设置状态正在采购
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            // id批量更新
            purchaseDetailService.updateBatchById(collect1);
        });

    }

    @Override
    public List<PurchaseEntity> getPurchases() {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0)
                .or()
                .eq("status",1);
        return this.list(wrapper);
    }

    /**
     * 完成采购单
     * @param purchaseDoneVo
     */
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        Long purchaseId = purchaseDoneVo.getId();
        boolean flag = true; //用于判断采购单是否完成
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntityList = new ArrayList<>();
        //遍历结果 , 改变采购项目的状态
        for (PurchaseItemDoneVo item:items
             ) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            // 如果采购失败
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            }else {
                // 3、将成功采购的进行入库
                PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(byId.getSkuId(),byId.getWareId(),byId.getSkuNum());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
            }
            purchaseDetailEntity.setId(String.valueOf(item.getItemId()));
            purchaseDetailEntityList.add(purchaseDetailEntity);
        }
        //修改采购单项状态
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(String.valueOf(purchaseId));
        // 设置状态根据变量判断采购是否完成
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        //修改采购单状态
        this.updateById(purchaseEntity);
    }

}